#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/stat.h>

#define N 4096

void send_headers(char *type)
{
    printf("HTTP/1.1 200 OK\r\n");
    printf("Content-Type: %s\r\n", type);
    printf("Connection: close\r\n");
    printf("\r\n");
}

void send_err(int err_code, char *err_name, char *err_text)
{
    send_headers("text/html; charset=iso-8859-1");

    printf("<html><title>%d %s</title></head><body>%s</body></html>", err_code, err_name, err_text);

    fflush(stdout);
    exit(1);
}

int main(int argc, char **argv)
{
    char line[N];
    char method[N], path[N], protocol[N];

    char *file;
    struct stat sbuf;
    FILE *fp;
    int ich;

    if (argc != 2)
    {
        send_err(500, "Internal Error", "Config error - no dir specified.");
    }

    if (chdir(argv[1]) == -1)
    {
        send_err(500, "Internal Error", "Config error - couldn't chdir().");
    }

    if (fgets(line, N, stdin) == NULL)
    {
        send_err(400, "Bad Request", "No request found.");
    }

    if (sscanf(line, "%[^ ] %[^ ] %[^ ]", method, path, protocol) != 3)
    {
        send_err(400, "Bad Request", "Can't parse request.");
    }

    while (fgets(line, N, stdin) != NULL)
    {
        if (strcmp(line, "\r\n"))
        {
            break;
        }
    }

    if (strcmp(method, "GET") != 0)
    {
        send_err(400, "Bad Request", "Request unsupported.");
    }

    if (path[0] != '/')
    {
        send_err(400, "Bad Request", "No path found.");
    }

    file = path + 1;

    if (stat(file, &sbuf) < 0)
    {
        send_err(400, "Bad Request", "No file found.");
    }

    fp = fopen(file, "r");
    if (fp == NULL)
    {
        send_err(500, "Internal Error", "File open error.");
    }

    send_headers("text/html; charset=iso-8859-1");

    while ((ich = getc(fp)) != EOF)
    {
        putchar(ich);
    }

    fflush(stdout);
    fclose(fp);

    return 0;
}